package com.zkool.train.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by zhaokui on 2019/8/10.
 */
public class TrainUtil {

    /**
     * 车次信息
     * keyword: 车次编号
     * date: yyyymmdd
     * return: {"data":[{"date":"20190811","from_station":"包头","station_train_code":"2462","to_station":"临汾","total_num":"26","train_no":"33000024620K"}],"status":true,"errorMsg":""}
     */
    private final static String SEARCH_TRAIN_NO_URL = "https://search.12306.cn/search/v1/train/search?keyword=%s&date=%s";

    /**
     * 时刻表/车次站点信息
     * leftTicketDTO.train_no: 车次序号
     * leftTicketDTO.train_date: yyyy-mm-dd
     * rand_code: 空
     * return: {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{
     * "data":[
     * {"arrive_day_str":"当日到达","arrive_time":"16:44","station_train_code":"2462","station_name":"包头","arrive_day_diff":"0",          "start_time":"16:44","wz_num":"--","station_no":"01","running_time":"00:00","train_class_name":"普快","is_start":"Y","service_type":"1","end_station_name":"临汾","start_station_name":"包头"},
     * {"arrive_day_str":"当日到达","arrive_time":"16:59","station_train_code":"2462","station_name":"包头东","arrive_day_diff":"0","OT":[],"start_time":"17:03","wz_num":"--","station_no":"02","running_time":"00:15"},
     * {"arrive_day_str":"次日到达","arrive_time":"08:14","station_train_code":"2463","station_name":"洪洞","arrive_day_diff":"1","OT":[],"start_time":"08:17","wz_num":"--","station_no":"25","running_time":"15:30"},
     * {"arrive_day_str":"次日到达","arrive_time":"08:40","station_train_code":"2463","station_name":"临汾","arrive_day_diff":"1","OT":[],"start_time":"08:40","wz_num":"--","station_no":"26","running_time":"15:56"}
     * ]},
     * "messages":[],"validateMessages":{}}
     */
    private final static String SEARCH_TRAIN_STATION_URL = "https://kyfw.12306.cn/otn/queryTrainInfo/query?leftTicketDTO.train_no=%s&leftTicketDTO.train_date=%s&rand_code=";

    /**
     * 地理编码 API 服务地址
     * key: 您的key
     * address: 结构化地址信息 规则遵循：国家、省份、城市、区县、城镇、乡村、街道、门牌号码、屋邨、大厦，如：北京市朝阳区阜通东大街6号
     * city: 指定查询的城市 可选输入内容包括：指定城市的中文（如北京）、指定城市的中文全拼（beijing）、citycode（010）、adcode（110000），不支持县级市。当指定城市查询内容为空时，会进行全国范围内的地址转换检索
     * return: {"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":[{"formatted_address":"内蒙古自治区乌兰察布市集宁区集宁南站","country":"中国","province":"内蒙古自治区","citycode":"0474","city":"乌兰察布市","district":"集宁区","township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"150902","street":[],"number":[],"location":"113.099434,41.030830","level":"兴趣点"}]}
     */
    private final static String GEOCODE_URL = "https://restapi.amap.com/v3/geocode/geo?key=xxx&address=%s&city=";

    /**
     * 根据车次编号获取车次序号
     * @param trainCode
     * @return
     */
    public static JSONObject getTrainNo(String searchTrainNoUrl, String trainCode){
        String url = String.format(searchTrainNoUrl, trainCode, date2Str(tomorrow(new Date()), "yyyyMMdd"));
        String body = getHttpReq(url);
        if(body != null){
            JSONObject result = JSON.parseObject(body);
            if(result.getBooleanValue("status")){
                JSONArray data = result.getJSONArray("data");
                if(data != null && data.size() > 0){
                    return data.getJSONObject(0);
                }
            }
        }
        return null;
    }

    /**
     * 根据车次序号获取站点信息
     * @param trainNo
     * @return
     */
    public static JSONArray getTrainStation(String searchTrainStationUrl, String trainNo){
        String url = String.format(searchTrainStationUrl, trainNo, date2Str(tomorrow(new Date()), "yyyy-MM-dd"));
        String body = getHttpReq(url);
        if(body != null){
            JSONObject result = JSON.parseObject(body);
            if(result.getBooleanValue("status")){
                JSONObject data = result.getJSONObject("data");
                if(data != null){
                    JSONArray datas = data.getJSONArray("data");
                    if(datas != null && datas.size() > 0){
                        return datas;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 根据地址返回地理编码数据
     * @param address
     * @return
     */
    public static JSONObject geoCode(String gencodeUrl, String address){
        String url = String.format(gencodeUrl, address);
        String body = getHttpReq(url);
        if(body != null){
            JSONObject result = JSON.parseObject(body);
            if(result.getIntValue("status") == 1){
                JSONArray geocodes = result.getJSONArray("geocodes");
                if(geocodes != null && geocodes.size() > 0){
                    return geocodes.getJSONObject(0);
                }
            }
        }
        return null;
    }

    /**
     * get请求
     * @param url
     * @return
     */
    public static String getHttpReq(String url){
        System.out.println("url = [" + url + "]");
        Request.Builder builder = new Request.Builder();
        builder.url(url).get();
        OkHttpClient client  = new OkHttpClient();
        Call call = client.newCall(builder.build());
        try{
            Response response = call.execute();
            String res = response.body() != null ? response.body().string() : null;
            System.out.println("body = [" + res + "]");
            return res;
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回明天
     * @param today
     * @return
     */
    public static Date tomorrow(Date today) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
        return calendar.getTime();
    }

    /**
     *
     * @param date
     * @param format yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String date2Str(Date date, String format){
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(date);
    }

    public static void main(String[] args) {
        System.out.println("==="+geoCode(GEOCODE_URL,"北京西站"));
    }

}
